//
//  SEGElevatorControlViewController.m
//  SEGUhomeIntelligentHardware
//
//  Created by 刘山 on 2018/4/26.
//  Copyright © 2018年 刘山. All rights reserved.
//

#import "SEGElevatorControlViewController.h"

#import "SEGElevatorControllAlertView.h"
#import "SEGElevatorControlCell.h"
#import "SEGElevatorControlHeader.h"
#import "SEGDoorQRCodeView.h"

#import "SEGOpenDoorBussinessManager.h"
#import "SEGElevatorControlViewModel.h"

static NSString *const kCellId = @"cellId";
static NSString *const kCellHeaderId = @"cellHeaderId";

@interface SEGElevatorControlViewController()<SEGprotocolElevatorControllAlertViewDelegate ,UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
 
/// 表格
@property (nonatomic, strong) UICollectionView *collectionView;
/// 描述
@property (nonatomic, strong) UILabel *descLabel;
/// 当前选择的楼层二维码数据 (失败时刷新使用)
@property (nonatomic, strong) SEGDoorQRCodeView *qrcodeView;

/// viewModel
@property (nonatomic, strong) SEGElevatorControlViewModel *viewModel;
/// disposable
@property (nonatomic, strong) RACDisposable *disposable;

@end

@implementation SEGElevatorControlViewController

- (void)dealloc {
    [SVProgressHUD dismiss];
    [self.disposable dispose];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = kColor_W;
    [self showCustomNavigationBackButton];
    self.title = self.title.length>0?self.title:@"电梯控制";
    [self segInit];
    [self segQequestData];
}

#pragma mark - Load Data
// 查询梯控列表数据
-(void)segQequestData {
    @weakify(self);
    [SVProgressHUD show];
    [self.viewModel.listSignal subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [SVProgressHUD dismiss];
        [self.collectionView reloadData];
    }];
}
// 获取二维码梯控
- (void)getElevGroupQrCodeWithElevId:(NSString *)elevId floor:(NSString *)floor directionFlag:(NSString *)directionFlag {
    RACTuple *tuple = RACTuplePack(elevId, floor, directionFlag);
    @weakify(self);
    [[self.viewModel.qrCodeCommand execute:tuple] subscribeNext:^(NSNumber *isSuccessed) {
        @strongify(self);
        [self seg_showQeCodeView:isSuccessed.boolValue];
    }];
}
- (void)seg_showQeCodeView:(BOOL)isSuccessed {
    BOOL isNeedRefresh = NO;
    if (!isSuccessed) isNeedRefresh = YES;
    if (!self.qrcodeView) {
        SEGDoorQRCodeView *qrCodeView = [[SEGDoorQRCodeView alloc] initWithFrame:CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight())];
        self.qrcodeView = qrCodeView;
    }
    self.qrcodeView.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight());
    self.qrcodeView.hidden = NO;
    NSString *qrCodeStr = isNeedRefresh ? @"" : self.viewModel.qrCodeStr;
    WeakSelf;
    [self.qrcodeView createQRCodeWithString:qrCodeStr doorName:@"" needRefresh:isNeedRefresh];
    if (isNeedRefresh) {
        self.qrcodeView.refreshBlock = ^{
            [weakSelf getElevGroupQrCodeWithElevId:weakSelf.viewModel.codeElevId floor:weakSelf.viewModel.codeFloor directionFlag:weakSelf.viewModel.codeDirectionFlag];
        };
    } else {
        self.qrcodeView.refreshBlock = nil;
    }
    [[UIApplication sharedApplication].keyWindow addSubview:self.qrcodeView];
}

#pragma mark - UI
-(void)segInit {
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.descLabel];
    [self.descLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).mas_offset(15);
        make.right.equalTo(self.view).mas_offset(-15);
        make.bottom.equalTo(self.view).mas_offset(-20);
    }];
}
/// 显示楼层弹窗
- (void)segAlertForChooseFloor:(NSArray<SEGFloorsModel *> *)floors elevId:(NSString *)elevId elevType:(NSString *)elevType keyU:(NSString *)keyU {
    // 所有楼层数据
    NSMutableArray *totalFloors = [NSMutableArray array];
    NSMutableArray *arrM = [NSMutableArray array];
    [floors enumerateObjectsUsingBlock:^(SEGFloorsModel*  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        SEGElevatorControllAlertFloorModel *data = [SEGElevatorControllAlertFloorModel new];
        data.businessData = obj;
        data.name = obj.manufacturerFloor;
        [arrM addObject:data];
        [totalFloors addObject:@[obj.floor, obj.directionFlag]];// 第一个元素标识楼层，第二个表示正北门，0是正门，1是背门
        _viewModel.floorArray = totalFloors;
    }];
    SEGElevatorControllAlertView * v = [SEGElevatorControllAlertView new];
    v.elevId = elevId;
    v.elevType = elevType;
    v.keyU = keyU;
    v.delegate = self;
    [v showWithData:arrM];
}

#pragma mark - SEGprotocolElevatorControllAlertViewDelegate 选中楼层代理回调
- (void)SEGprotocolDidSelectedRowData:(id)data elevId:(NSString *)elevId elevType:(NSString *)elevType keyU:(NSString *)keyU {
    @weakify(self);
    SEGFloorsModel *ret = (SEGFloorsModel *)data;
    RACTuple *tuple = RACTuplePack(ret, elevId, elevType, keyU);
    self.disposable = [[self.viewModel.callElevatorCommand execute:tuple] subscribeNext:^(NSNumber *status) {
        @strongify(self);
        if ([elevType isEqualToString:@"0"]) { // 蓝牙
            if (status.integerValue == SEGOpenDoorStatus_Begin) { // 开始呼梯
                [SVProgressHUD showWithStatus:@"电梯设备连接中，请稍等！"];
            } else if (status.integerValue == SEGOpenDoorStatus_Success) { // 成功
                [SVProgressHUD dismiss];
                [SEGAlertView showTmepMessageWithMessage:[NSString stringWithFormat:@"正在前往%@楼...",ret.manufacturerFloor]];
            } else if (status.integerValue == SEGOpenDoorStatus_Failed) { // 失败
                [SVProgressHUD dismiss];
                [SEGAlertView showTmepMessageWithMessage:@"没有发现电梯设备"];
            }
        } else { // 二维码
            [self getElevGroupQrCodeWithElevId:self.viewModel.codeElevId floor:self.viewModel.codeFloor directionFlag:self.viewModel.codeDirectionFlag];
        }
    } error:^(NSError * _Nullable error) { // 蓝牙未打开
        if (error.code == CBPeripheralManagerStateUnauthorized) {
            [SEGOpenDoorBussinessManager showOpenBluetoothAlterWithBluetoothState:CBPeripheralManagerStateUnauthorized];
        } else if (error.code == CBPeripheralManagerStatePoweredOff) {
            [SEGOpenDoorBussinessManager showOpenBluetoothAlterWithBluetoothState:CBPeripheralManagerStatePoweredOff];
        } else {
            [SEGAlertView showTmepMessageWithMessage:@"蓝牙异常"];
        }
    }];
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return self.viewModel.dataArr.count;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    SEGQueryGroupFloorByUserModel *model = self.viewModel.dataArr[section];
    return model.elevGroupList.count;
}
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SEGElevatorControlCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kCellId forIndexPath:indexPath];
    SEGQueryGroupFloorByUserModel *sectionModel = self.viewModel.dataArr[indexPath.section];
    SEGElevGroupListModel *model = sectionModel.elevGroupList[indexPath.row];
    [cell refreshCellWithModel:model];
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
        SEGElevatorControlHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kCellHeaderId forIndexPath:indexPath];
        SEGQueryGroupFloorByUserModel *model = self.viewModel.dataArr[indexPath.section];
        [header refreshCellWithTitle:model.buildUnit];
        return header;
    }
    return [UICollectionReusableView new];
}
#pragma mark - UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
    return CGSizeMake(kScreenWidth, kSEGElevatorControlHeader_H);
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
    return CGSizeZero;
}
#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    SEGQueryGroupFloorByUserModel *sectionModel = self.viewModel.dataArr[indexPath.section];
    SEGElevGroupListModel *model = sectionModel.elevGroupList[indexPath.row];
    if (model.floors.count == 0) {
        [SEGAlertView showTmepMessageWithMessage:@"网络开小差了，请稍后重试"];
        return;
    }
    [self segAlertForChooseFloor:model.floors elevId:model.elevId elevType:model.elevType keyU:sectionModel.keyU];
    // 获取电梯设备数组，用于设备搜索
    [self.viewModel seg_generatLevatorArrayForScanWithElevTag:model.elevTag];
}

#pragma mark - Getter
- (UICollectionView *)collectionView {
    if (!_collectionView) {
        CGRect rect = CGRectMake(0, 0, kScreenWidth, LYScreenHeight()-kNavigationBarAndStatusBarHeight-90);
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        CGFloat size_W = kScreenWidth/3;
        flowLayout.itemSize = CGSizeMake(size_W, LYDistanceV(110));
        flowLayout.minimumLineSpacing = 10;
        flowLayout.minimumInteritemSpacing = 0;
        _collectionView = [[UICollectionView alloc] initWithFrame:rect collectionViewLayout:flowLayout];
        _collectionView.backgroundColor = kColor_W;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.alwaysBounceVertical = YES;
        [_collectionView registerClass:[SEGElevatorControlCell class] forCellWithReuseIdentifier:kCellId];
        [_collectionView registerClass:[SEGElevatorControlHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kCellHeaderId];
    }
    return _collectionView;
}
- (UILabel *)descLabel {
    if (!_descLabel) {
        _descLabel = [[UILabel alloc]init];
        _descLabel.backgroundColor = kColor_W;
        _descLabel.userInteractionEnabled = NO;
        _descLabel.font = kFont_13;
        _descLabel.textColor = kColor_3;
        _descLabel.numberOfLines = 0;
        _descLabel.layer.masksToBounds = YES;
        _descLabel.lineBreakMode = NSLineBreakByTruncatingTail;
        if (kDebug)_descLabel.backgroundColor = kSegRandomColor;
        _descLabel.text = @"温馨提示：\n1、进入电梯并开启蓝牙后使用此功能；\n2、选择进入电梯的对应按钮；\n3、如有手机梯控故障，请与管理处联系。";
    }
    return _descLabel;
}
- (SEGElevatorControlViewModel *)viewModel {
    if (!_viewModel) _viewModel = [SEGElevatorControlViewModel new];
    return _viewModel;
}

@end
